import { ElMessage } from 'element-plus'
import { BASE_URL } from '@/utils/zongID';
// 导入element的图标FolderAdd组件
import { FolderAdd } from '@element-plus/icons-vue'

export default {
    name: 'FileUpload',
    props: {
        exampleFileSelected: {
            type: Boolean,
            default: false
        },
        modelValue: {
            type: Array,
            default: () => []
        },
        resMsg: {
            type: String,
            default: ''
        },
        id: {
            type: String,
            default: ''
        },
        isUploading: {
            type: Boolean,
            default: false
        }
    },
    components: {
        FolderAdd
    },
    data() {
        return {
            uploading: false,
        }
    },
    computed: {
        files: {
            get() {
                return this.modelValue;
            },
            set(value) {
                this.$emit('update:modelValue', value);
            }
        }
    },
    watch: {
        isUploading(newVal) {
            if (newVal) {
                this.uploading = newVal;
            }
        },
        async exampleFileSelected(newVal) {
            if (newVal) {
                try {
                    const response = await fetch('/商圈数据.csv');
                    const blob = await response.blob();
                    const file = new File([blob], '商圈数据.csv', {
                        type: 'application/pdf'
                    });
                    this.files = [file];
                } catch (error) {
                    console.error('加载示例文件失败:', error);
                }
            } else {
                this.files = [];
            }
        }
    },
    methods: {
        async handleFileUpload(event) {
            const newFiles = Array.from(event.target.files);
            console.log("xixxxxxxxxx", newFiles);
            
            if (newFiles.length) {
                console.log("准备赋值 this.files");
                this.files = [newFiles[0]];
                const formData = new FormData();
                formData.append('file', newFiles[0]);
                console.log("this.files 已赋值:", this.files);

                this.uploading = true;
                this.$emit('update:is-uploading', true);
                // const formData = new FormData();
                // this.files.forEach(file => {
                //     console.log(file);
                //     formData.append('file', file);
                // });
    
    
    
    
                try {
                    const response = await fetch(`${BASE_URL}/api/fuxigen-sessionid`, {
                        method: 'POST',
                        body: formData
                    });
    
                    if (response.ok) {
                        ElMessage.success('文件上传成功')
                        const res = await response.json();
                        console.log(res);
                        this.$emit('update:resMsg', res.message);
                        this.$emit('update:id', res.session_id);
    
    
                    } else {
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.error('上传文件时出错:', error);
                    ElMessage.error('上传文件失败，请重试');
                } finally {
                    this.$emit('update:is-uploading', false);
                    this.uploading = false;
                }





            } else {
                console.warn("没有选择文件");
            }
            
            
            
            
            
            // this.uploading = true;
            // this.$emit('update:is-uploading', true);
            // // const formData = new FormData();
            // // this.files.forEach(file => {
            // //     console.log(file);
            // //     formData.append('file', file);
            // // });




            // try {
            //     const response = await fetch(`${BASE_URL}/api/fuxigen-sessionid`, {
            //         method: 'POST',
            //         body: formData
            //     });

            //     if (response.ok) {
            //         ElMessage.success('文件上传成功')
            //         const res = await response.json();
            //         console.log(res);
            //         this.$emit('update:resMsg', res.message);
            //         this.$emit('update:id', res.session_id);


            //     } else {
            //         throw new Error('上传失败');
            //     }
            // } catch (error) {
            //     console.error('上传文件时出错:', error);
            //     ElMessage.error('上传文件失败，请重试');
            // } finally {
            //     this.$emit('update:is-uploading', false);
            //     this.uploading = false;
            // }





        },
        handleDrop(event) {
            const newFiles = Array.from(event.dataTransfer.files).filter(
                file => file.name.endsWith('.csv') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
            );
            this.files = [...this.files, ...newFiles];
        },
        triggerFileInput() {
            this.$emit('update:exampleFileSelected', false);
            this.$refs.fileInput.click();
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        },
        removeFile(index) {
            this.files.splice(index, 1);
        },
        downloadFile(file) {
            const url = URL.createObjectURL(file);
            const a = document.createElement('a');
            a.href = url;
            a.download = file.name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        },
        async handleProcessFiles() {
            if (this.files.length === 0) {
                ElMessage.success('请选择文件')
                return;
            }

            const formData = new FormData();
            this.files.forEach(file => {
                formData.append('file', file);
            });
            this.uploading = true;

            try {
                const response = await fetch(`${BASE_URL}/api/fuxigen-sessionid`, {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    ElMessage.success('文件上传成功')
                    const res = await response.json();
                    console.log(res);
                    this.$emit('update:resMsg', res.message);
                    this.$emit('update:id', res.session_id);
                    this.$emit('update:is-uploading', true);

                } else {
                    throw new Error('上传失败');
                }
            } catch (error) {
                console.error('上传文件时出错:', error);
                ElMessage.error('上传文件失败，请重试');
            } finally {
                this.$emit('update:is-uploading', false);
                this.uploading = false;
            }
        }
    }
}